package git.soulbgm.pojo;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2019-04-09 14:52
 * @description 动态实体Bean
 */
public class CglibBean {

    /**
     * 实体Object
     */
    private Object object = null;

    /**
     * 属性map
     */
    private BeanMap beanMap = null;

    public CglibBean() {
        super();
    }

    public CglibBean(Map<String, Class> beanMap) {
        this.object = generateBean(beanMap);
        this.beanMap = BeanMap.create(object);
    }

    /**
     * 给bean属性赋值
     *
     * @param property 属性名
     * @param value    值
     */
    public void setValue(String property, Object value) {
        beanMap.put(property, value);
    }

    /**
     * 通过属性名得到属性值
     *
     * @param property
     * @return
     */
    public Object getValue(String property) {
        return beanMap.get(property);
    }

    /**
     * 得到该实体bean对象。
     */
    public Object getObject() {
        return object;
    }

    /**
     * 生成Bean
     * @param propertyMap
     * @return
     */
    private Object generateBean(Map<String, Class> propertyMap) {
        BeanGenerator generator = new BeanGenerator();
        Set keySet = propertyMap.keySet();
        for (Object o : keySet) {
            String key = (String) o;
            generator.addProperty(key, (Class) propertyMap.get(key));
        }
        return generator.create();
    }
}
